import {
  Button,
  Form,
  Message,
  Modal,
  Select,
  Space,
} from "@arco-design/web-react";
import { css } from "@emotion/css";
import { FC, useMemo, useState } from "react";
import { Role, SystemUserDataRow } from "../../api/types/system-user.ts";
import { useMutation, useQuery } from "react-query";
import { SearchBuildingParams } from "../../api/types/building.tsx";
import { useAPI } from "../../hooks/useAPI.ts";
import { SearchRiskTypeParams } from "../../api/types/elder-risk.ts";

export const elderListParams: SearchRiskTypeParams = {
  pageNum: 1,
  pageSize: 1000,
  roleIds: Role.ElderUser,
};

export const bedList = [
  {
    label: "左床",
    value: 0,
  },
  {
    label: "中床",
    value: 1,
  },
  {
    label: "右床",
    value: 2,
  },
];

export interface BindElderAndRoomModalProps {
  visible?: boolean;
  onClose?: () => void;
  onSuccess?: () => void;
  onAddElder?: () => void;
  onAddBuilding?: () => void;
  title?: string;
  defaultData?: SystemUserDataRow | null | undefined;
}

export const BindElderAndRoomModal: FC<BindElderAndRoomModalProps> = ({
  visible,
  onClose,
  title,
  onSuccess,
  onAddElder,
  onAddBuilding,
  defaultData,
}) => {
  const api = useAPI();
  const [formRef] = Form.useForm();
  const selectedBuildingId = Form.useWatch("buildingId", formRef);
  const selectedFloorId = Form.useWatch("floorId", formRef);
  const [elderIsNotExists, setElderIsNotExists] = useState(false);
  const [buildingIsNotExists, setBuildingIsNotExists] = useState(false);
  const buildingListParams: SearchBuildingParams = {
    pageNum: 1,
    pageSize: 1000,
  };

  const { data: buildingList } = useQuery(
    ["query-building-list", buildingListParams],
    async () => {
      const response = await api.getBuildingList(buildingListParams);
      if (!response.data.data) {
        throw new Error("No Data");
      }
      return response.data.data;
    }
  );

  const { data: buildingInfo } = useQuery(
    ["query-building-info", selectedBuildingId],
    async () => {
      const response = await api.getBuildingInfoById(selectedBuildingId);
      if (!response.data.data) {
        throw new Error("No Data");
      }
      return response.data.data;
    },
    {
      enabled: selectedBuildingId !== undefined,
    }
  );

  const { data: elderList } = useQuery(
    ["query-elder-list", elderListParams],
    async () => {
      const response = await api.getSystemUserList({ ...elderListParams });
      if (!response.data.data) {
        throw new Error("No Data");
      }
      return response.data.data;
    }
  );

  const rooms = useMemo(() => {
    const floor = buildingInfo?.floors?.find(
      (floor) => floor.id === selectedFloorId
    );
    if (!floor) return [];
    return floor.rooms;
  }, [buildingInfo?.floors, selectedFloorId]);

  const submitForm = useMutation(async () => {
    try {
      const values = await formRef.validate();
      const { userId, roomId, location } = values;
      const payload = { id: roomId, userId: userId, location: location };
      const response = await api.updateRooms(payload);
      const response2 = await api.bindActionTable(payload);
      if (response.data.data && response2.data.data) {
        if (onSuccess) onSuccess();
        Message.success("操作成功");
      } else {
        Message.error("操作失败");
      }
      formRef.resetFields();
    } catch (error) {
      if (elderIsNotExists) {
        onAddElder?.();
        return;
      }
      if (buildingIsNotExists) {
        onAddBuilding?.();
        return;
      }
      if (error instanceof Error) {
        Message.error(error.message);
      } else {
        Message.error("操作失败，请稍后重试");
      }
    }
  });

  return (
    <Modal
      title={title ? title : "编辑长辈信息"}
      footer={null}
      visible={visible}
      onCancel={() => {
        formRef.resetFields();
        onClose?.();
      }}
    >
      {defaultData && (
        <Form form={formRef} initialValues={defaultData}>
          <Form.Item
            label="长辈"
            field="userId"
            rules={[
              {
                required: true,
                validator(value, cb) {
                  if (!value) {
                    return cb("长辈不得为空");
                  }
                  const isNotExists =
                    elderList?.rows.findIndex((v) => value === v.userId) === -1;
                  setElderIsNotExists(isNotExists);
                  if (isNotExists) {
                    return cb("长辈不存在");
                  }
                  cb(null);
                },
              },
            ]}
          >
            <Select
              placeholder="请选择长辈"
              allowClear
              options={elderList?.rows.map((item) => ({
                label: item.nickName,
                value: item.userId,
              }))}
              allowCreate
              showSearch
              filterOption={(input, option) =>
                option?.props.children
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>

          <Form.Item
            label="楼栋"
            field="buildingId"
            rules={[
              {
                required: true,
                validator(value, cb) {
                  if (!value) {
                    return cb("楼栋不得为空");
                  }
                  const isBuildingNotExists =
                    buildingList?.rows.findIndex((v) => value === v.id) === -1;
                  setBuildingIsNotExists(isBuildingNotExists);
                  if (isBuildingNotExists) {
                    return cb("楼栋不存在");
                  }
                  cb(null);
                },
              },
            ]}
          >
            <Select
              placeholder="请选择楼栋"
              options={buildingList?.rows.map((item) => ({
                label: item.name,
                value: item.id,
              }))}
              showSearch
              allowClear
              allowCreate
              onChange={async (value) => {
                await api.getBuildingInfoById(value!);
                formRef.setFieldsValue({
                  floorId: undefined,
                  roomId: undefined,
                });
              }}
              filterOption={(input, option) =>
                option?.props.children
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>
          <Form.Item
            label="楼层"
            field="floorId"
            rules={[
              {
                required: true,
                message: "楼层不得为空",
              },
            ]}
          >
            <Select
              placeholder="请选择楼层"
              disabled={!selectedBuildingId}
              options={buildingInfo?.floors?.map((item) => ({
                label: item.name,
                value: item.id,
              }))}
              allowClear
              showSearch
              filterOption={(input, option) =>
                option?.props.children
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>
          <Form.Item
            label="房间号"
            field="roomId"
            rules={[
              {
                required: true,
                message: "房间不得为空",
              },
            ]}
          >
            <Select
              placeholder="请选择房间号"
              disabled={!selectedFloorId}
              options={rooms?.map((item) => ({
                label: item.name,
                value: item.id,
              }))}
              allowClear
              showSearch
              filterOption={(input, option) =>
                option?.props.children
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>
          <Form.Item label="床位" field="location">
            <Select
              placeholder="请选择床位"
              options={bedList.map((item) => ({
                label: item.label,
                value: item.value,
              }))}
              showSearch
              filterOption={(input, option) =>
                option?.props.children
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>

          <Space
            className={css`
              margin-top: 16px;
              padding: 12px 0;
              display: flex;
              justify-content: end;
            `}
          >
            <Button
              type="outline"
              htmlType="button"
              onClick={() => {
                formRef.resetFields();
                onClose?.();
              }}
            >
              取消
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              loading={submitForm.isLoading}
              onClick={() => submitForm.mutateAsync()}
            >
              完成
            </Button>
          </Space>
        </Form>
      )}
      {!defaultData && (
        <Form form={formRef}>
          <Form.Item
            label="长辈"
            field="userId"
            rules={[
              {
                required: true,
                validator(value, cb) {
                  if (!value) {
                    return cb("长辈不得为空");
                  }
                  const isNotExists =
                    elderList?.rows.findIndex((v) => value === v.userId) === -1;
                  setElderIsNotExists(isNotExists);
                  if (isNotExists) {
                    return cb("长辈不存在");
                  }
                  cb(null);
                },
              },
            ]}
          >
            <Select
              placeholder="请选择长辈"
              allowClear
              options={elderList?.rows.map((item) => ({
                label: item.nickName,
                value: item.userId,
              }))}
              allowCreate
              showSearch
              filterOption={(input, option) =>
                option?.props.children
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>

          <Form.Item
            label="楼栋"
            field="buildingId"
            rules={[
              {
                required: true,
                validator(value, cb) {
                  if (!value) {
                    return cb("楼栋不得为空");
                  }
                  const isBuildingNotExists =
                    buildingList?.rows.findIndex((v) => value === v.id) === -1;
                  setBuildingIsNotExists(isBuildingNotExists);
                  if (isBuildingNotExists) {
                    return cb("楼栋不存在");
                  }
                  cb(null);
                },
              },
            ]}
          >
            <Select
              placeholder="请选择楼栋"
              options={buildingList?.rows.map((item) => ({
                label: item.name,
                value: item.id,
              }))}
              showSearch
              allowClear
              allowCreate
              onChange={async (value) => {
                await api.getBuildingInfoById(value!);
                formRef.setFieldsValue({
                  floorId: undefined,
                  roomId: undefined,
                });
              }}
              filterOption={(input, option) =>
                option?.props.children
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>
          <Form.Item
            label="楼层"
            field="floorId"
            rules={[
              {
                required: true,
                message: "楼层不得为空",
              },
            ]}
          >
            <Select
              placeholder="请选择楼层"
              disabled={!selectedBuildingId}
              options={buildingInfo?.floors?.map((item) => ({
                label: item.name,
                value: item.id,
              }))}
              allowClear
              showSearch
              filterOption={(input, option) =>
                option?.props.children
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>
          <Form.Item
            label="房间号"
            field="roomId"
            rules={[
              {
                required: true,
                message: "房间不得为空",
              },
            ]}
          >
            <Select
              placeholder="请选择房间号"
              disabled={!selectedFloorId}
              options={rooms?.map((item) => ({
                label: item.name,
                value: item.id,
              }))}
              allowClear
              showSearch
              filterOption={(input, option) =>
                option?.props.children
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>
          <Form.Item label="床位" field="location">
            <Select
              placeholder="请选择床位"
              options={bedList.map((item) => ({
                label: item.label,
                value: item.value,
              }))}
              showSearch
              filterOption={(input, option) =>
                option?.props.children
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>

          <Space
            className={css`
              margin-top: 16px;
              padding: 12px 0;
              display: flex;
              justify-content: end;
            `}
          >
            <Button
              type="outline"
              htmlType="button"
              onClick={() => {
                formRef.resetFields();
                onClose?.();
              }}
            >
              取消
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              loading={submitForm.isLoading}
              onClick={() => submitForm.mutateAsync()}
            >
              完成
            </Button>
          </Space>
        </Form>
      )}
    </Modal>
  );
};
